package cn.jhh.content.service.impl;

import cn.jhh.content.model.dto.SaveTeachPlanDto;
import cn.jhh.content.model.dto.TeachplanDto;
import cn.jhh.content.model.entity.Teachplan;
import cn.jhh.content.mapper.TeachplanMapper;
import cn.jhh.content.service.TeachplanService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程计划 服务实现类
 * </p>
 *
 * @author jhh
 * @since 2025-05-23
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {
    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {
        List<TeachplanDto> teachplanDtos =baseMapper.selectTreeNodes(courseId);
        return teachplanDtos;
    }

    @Override
    public void saveTeachplan(SaveTeachPlanDto dto) {
        Teachplan teachPlan = getById(dto.getId());
        if(teachPlan == null){
            teachPlan = new Teachplan();
            BeanUtils.copyProperties(dto,teachPlan);
//            找到同级课程计划的数量
            long count = getTeachplanCount(dto.getCourseId(), dto.getParentid());
//          新课程计划的值
            teachPlan.setOrderby(Integer.getInteger("" + (count + 1)));
            save(teachPlan);
        }else{
            BeanUtils.copyProperties(dto,teachPlan);
            updateById(teachPlan);
        }
    }

    private long getTeachplanCount(Long courseId, Long parentid) {
        return count(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId,courseId).eq(Teachplan::getParentid,parentid));
    }
}
